package com.xl.bigdata.es.xpack;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: IAEngine
 * @description:
 * 在 Elasticsearch 7.0 中不建议使用TransportClient，并且在8.0中会完全删除TransportClient。
 * 因此，官方更建议我们用Java High Level REST Client，它执行HTTP请求，
 * 而不是序列号的Java请求。既然如此，这里就直接用高级了。
 * @author: XL.Gao
 * @create: 2021-08-23 10:06
 **/
public class ESXpackRestHighLevelClient {


    public  static volatile RestHighLevelClient client = null;

    public static String servers = "10.155.20.101,10.155.20.102,10.155.20.103";

    public static String username = "elastic";

    public static String password = "123456";

    public static int port = 49200;

    public static RestHighLevelClient getRestHighLevelClient(){

        if(client == null){

            synchronized (ESXpackRestHighLevelClient.class){
                if(client == null){

                    final CredentialsProvider credentialsProvider =
                            new BasicCredentialsProvider();
                    credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));

                    List<HttpHost> list = new ArrayList<>();
                    if(servers.contains(",")){
                        String[] split = servers.split(",");
                        for(String ip : split){
                            list.add(new HttpHost(ip, port));
                        }
                    } else {
                        list.add(new HttpHost(servers, port));
                    }

                    HttpHost[] httpHosts = new HttpHost[list.size()];
                    RestClientBuilder restClientBuilder = RestClient.builder(list.toArray(httpHosts));

                    RestClientBuilder builder = restClientBuilder
                            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

                    client = new RestHighLevelClient(builder);

                    System.out.println("ESXpackRestHighLevelClient初期化成功...");

                }
            }

        } else {
            System.out.println("ESXpackRestHighLevelClient重复使用中...");
        }

        return client;

    }

    public static String getIndex(String index, String id){
        GetRequest request = new GetRequest(index, id);
        GetResponse getResponse = null;
        try {
            getResponse = client.get(request, RequestOptions.DEFAULT);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return getResponse.getSourceAsString();
    }

    /*
     * 功能描述: <br>
     * FSC ->  FetchSourceContext
     *      in
     * @Param: [index, id]
     * @Return: java.lang.String
     * @Author: XL.Gao
     * @Date: 2021/8/25 16:31
     */
    public static String getIndexUseFSC(String index, String id,String ... includesField){

        // 搜索结果包含哪些字段
        // 搜索结果排除哪些字段
        String[] excludes = Strings.EMPTY_ARRAY;

        FetchSourceContext fetchSourceContext =
                new FetchSourceContext(true, includesField, excludes);

        GetRequest request = new GetRequest(index, id);
        request.fetchSourceContext(fetchSourceContext);
        GetResponse getResponse = null;
        try {
            getResponse = client.get(request, RequestOptions.DEFAULT);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return getResponse.getSourceAsString();
    }

    public static synchronized void closeRestHighLevelClient(){
        if(client != null){
            try {
                client.close();
                System.out.println("ESXpackRestHighLevelClient关闭成功...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {

        // 禁用日志打印
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.detachAndStopAllAppenders();
        });

        getRestHighLevelClient();

        System.out.println(getIndex("workorder_photo_v1", "oTg5lnsBwWkyB-mwZFrK"));


        closeRestHighLevelClient();

    }
}
